package com.baizhi.action;

import com.baizhi.entity.User;
import com.baizhi.service.UserService;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;

@Controller("userAction")
@Scope("prototype")
public class UserAction extends ActionSupport {
    /*成员变量*/
   private User user;
   private String code;
   private String codeuser;
   private String coderegister;

   @Autowired
   private UserService userService;

   /*登录*/
   public String login(){

       String username = user.getUsername();
       String password = user.getPassword();
       System.out.println(username+"-----"+ password);

       Map<String,Object> session = ActionContext.getContext().getSession();
       session.put("username",username);
       session.put("user",user);

       //自动生成
       String code = (String) session.get("code");
       System.out.println(code);


       User user = userService.queryByNameAndPassword(username,password);
       System.out.println(user);

       if (user!=null && codeuser.equals(code)){
           return "loginSuccess";
       }
       return "exitsuccess";
   }


   /*注册*/
    public String register(){

        HttpServletRequest request =ServletActionContext.getRequest();
        HttpSession session = request.getSession();

        //获取自动生成的验证码
        String code = (String) session.getAttribute("code");
        System.out.println(code);


        //如果输入用户名密码， 并且验证码正确，注册用户
        if (user !=null && coderegister.equals(code)) {
            userService.add(user);

            return "registerSuccess";
        }

        return "exitsuccess";
    }


    /*安全退出*/
    public String exit(){

        HttpSession session = ServletActionContext.getRequest().getSession();
        session.invalidate();  //销毁session  跳转到login.jsp

        return "exitsuccess";
    }



    /*get/set*/
    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getCodeuser() {
        return codeuser;
    }

    public void setCodeuser(String codeuser) {
        this.codeuser = codeuser;
    }

    public String getCoderegister() {
        return coderegister;
    }

    public void setCoderegister(String coderegister) {
        this.coderegister = coderegister;
    }
}
